﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ScanADocument.SaveScannedImages;
using System.Windows.Browser;
using System.IO;
using System.Net.Browser;


namespace ScanADocument
{
    [ScriptableType()]
    public partial class MainPage : UserControl
    {
        
        string strCurrentUri = "";
        public MainPage()
        {
            //bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            InitializeComponent();



            getServiceUri();

            HtmlPage.RegisterScriptableObject("Page", this);

            
        }


        /// <summary>
        /// this function will get the service uri for the application
        /// </summary>
        private void getServiceUri()
        {
            strCurrentUri = HtmlPage.Document.DocumentUri.AbsoluteUri;

            string strFilePart = System.IO.Path.GetFileName(strCurrentUri);
            strCurrentUri = strCurrentUri.Substring(0, strCurrentUri.Length - (strFilePart.Length + 1));
            strCurrentUri = strCurrentUri + "/../ScannedImagesWcf/SaveScannedImages.svc";

                        
        }

        [ScriptableMember()]
        public void startScan(string strButtonName, long Attachment_ID,long port)
        {
            if (currentStatus == null)
                currentStatus = false;
            
                if (currentStatus == false)
                {
                    currentStatus = true;
                    Uri scannerUri = new Uri("http://localhost:"+ port.ToString() +"/scan");

                    var client = new WebClient();

                    currentAttachment_ID = Attachment_ID;
                    currentButton = strButtonName;
                    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                    client.OpenReadAsync(scannerUri);
                }
        }

        private bool? currentStatus = null;
        private long? currentAttachment_ID = null;
        private string currentButton = "";

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveScannedImagesClient proxy = new SaveScannedImagesClient();
            proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(strCurrentUri);



            proxy.HelloWorldCompleted += new EventHandler<HelloWorldCompletedEventArgs>(proxy_HelloWorldCompleted);

            proxy.HelloWorldAsync();



            // Uri scannerUri = new Uri("http://localhost:8888/scan");

            //var client = new WebClient();
            //client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            //client.OpenReadAsync(scannerUri);
		}

        private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (currentAttachment_ID == null)
            {
                MessageBox.Show("خطأ في حفظ البيانات , حاول مرة اخرى!");
                return;
            }

            List<byte[]> lstNew = new List<byte[]>();


            Stream s = e.Result;


           

            byte[] btAll = new byte[s.Length];

            s.Read(btAll, 0, btAll.Length);











            SaveScannedImagesClient proxy = new SaveScannedImagesClient();
            proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(strCurrentUri);




            proxy.saveImagesCompleted += new EventHandler<saveImagesCompletedEventArgs>(proxy_saveImagesCompleted);




            proxy.saveImagesAsync(btAll,currentAttachment_ID.Value);





            

        }



        void proxy_saveImagesCompleted(object sender, saveImagesCompletedEventArgs e)
        {
            long file_Id = -1;
            try
            {
                int count = int.Parse(e.Result.Split(',')[0]);
                MessageBox.Show("تم اضافة عدد " + count + " صورة");

                 file_Id = int.Parse(e.Result.Split(',')[1]);

            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString()+" خطأ في الاتصال بالخادم ! ");
            }


            ScriptObject htmlDoPostBack = (ScriptObject)HtmlPage.Window.GetProperty("mySilverLightDoPostBack");

            if (currentButton == "")
                htmlDoPostBack.InvokeSelf("", "");
            else
                htmlDoPostBack.InvokeSelf(currentButton.Replace("_", "$"), "");

            currentStatus = false;

            HtmlDocument doc = HtmlPage.Document;
            doc.GetElementById("ctl00_HiddenFieldSilverLight");
            doc.SetProperty("value", file_Id);


        }




        void proxy_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
        {
            try
            {
                string result = e.Result;
                MessageBox.Show(result);
            }
            catch
            {
                MessageBox.Show("خطأ في الاتصال بالخادم!");
            }
        }
    }
}
